// 该文件涉及 token 的一些处理方法

const HISTORY = "history";

// 获取history
const getHistory = () => JSON.parse(localStorage.getItem(HISTORY));

// 设置history
const setHistory = (value) =>
  localStorage.setItem(HISTORY, JSON.stringify(value));

// 判断是否有历史记录
const hasHistory = () => !!getHistory();

const addHistory = (house) => {
  if (hasHistory()) {
    const oldHistory = getHistory();
    const newHistory = [];
    // 去重
    for (let h of oldHistory) {
      if (h.houseCode !== house.houseCode) {
        newHistory.push(h);
      }
    }
    // 限制浏览记录长度为100
    if (newHistory.length >= 100) {
      newHistory.pop();
    }
    newHistory.unshift(house);
    setHistory(newHistory);
  } else {
    setHistory([house]);
  }
};

export { addHistory, getHistory, setHistory, hasHistory };
